<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>子父组件传值2</title>
    <script src="../lib/vue_v2.6.14.js"></script>
  </head>
  <body>
    <div id="app">
      <cpn-son :list="list" @change="change"></cpn-son>
    </div>

    <template id="cpn">
      <div>
        <ul>
          <li v-for="(item, index) in list" :key="index">{{ item.name }}</li>
        </ul>
        <input type="text" v-model="inputVal" />
        <button @click="changeVal">添加</button>
      </div>
    </template>
    <script>
      // 子组件
      Vue.component('cpn-son', {
        template: '#cpn',
        props: {
          list: {
            type: Array,
            required: true
          }
        },
        data() {
          return {
            inputVal: ''
          }
        },
        methods: {
          changeVal() {
            this.$emit('change', this.inputVal)
          }
        }
      })

      // 父组件
      const vm = new Vue({
        el: '#app',
        data: {
          list: [
            { id: 1, name: '张三' },
            { id: 2, name: '李四' },
            { id: 3, name: '王五' },
            { id: 4, name: '赵六' }
          ]
        },
        methods: {
          // 子组件传过来的事件
          change(val) {
            const obj = {
              id: this.list[this.list.length - 1].id + 1,
              name: val
            }
            this.list.push(obj)
          }
        }
      })
    </script>
  </body>
</html>
